package com.chen.common.dataSource.config;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;
 
/**
 * 线程安全的动态数据源配置
 * @author ~龙~
 */
public class DataSourceThreadLocal extends AbstractRoutingDataSource {
    private static final ThreadLocal<String> DS_CONTEXT_HOLDER = new ThreadLocal<>();
 
    public DataSourceThreadLocal(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }
 
    @Override
    protected Object determineCurrentLookupKey() {
        return DS_CONTEXT_HOLDER.get();
    }
 
    public static void setDataSourceKey(String dataSourceKey) {
        DS_CONTEXT_HOLDER.set(dataSourceKey);
    }

    public static void del(){
        DS_CONTEXT_HOLDER.remove();
    }
}